package com.xuecheng.govern.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.govern.gateway.service.AuthService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginFilter extends ZuulFilter {

    @Autowired
    AuthService authService;
    //filterType：返回字符串代表过滤器的类型，如下
    // pre：请求在被路由之前执行
    // routing：在路由请求时调用
    // post：在routing和errror过滤器之后调用
    // error：处理请求时发生错误调用
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        //为false表示不执行过滤
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //获取request和response
        RequestContext requestContext=RequestContext.getCurrentContext();
        HttpServletRequest request= requestContext.getRequest();
        //取出Authorization
        String authorizationJwt=authService.getJwtFromHeader(request);
        if(StringUtils.isEmpty(authorizationJwt)){
            access_refuse();
        }
        String access_token=authService.getTokenFormCookie(request);
        if(StringUtils.isEmpty(access_token)){
            access_refuse();
        }
        //从redis中校验身份令牌是否过期
        long expire = authService.getExpire(access_token);
        if(expire<0){
            access_refuse();
        }
        return null;
    }

    //拒绝访问代码
    private void access_refuse(){
        //获取request和response
        RequestContext requestContext=RequestContext.getCurrentContext();
        HttpServletResponse response = requestContext.getResponse();
        requestContext.setSendZuulResponse(false);// 拒绝访问
        requestContext.setResponseStatusCode(200);// 设置响应状态码
        ResponseResult unauthenticated = new ResponseResult(CommonCode.UNAUTHENTICATED);
        String jsonString = JSON.toJSONString(unauthenticated);
        requestContext.setResponseBody(jsonString);
        response.setContentType("application/json;charset=UTF-8");
    }
}
